package com.charonmc.listeners;

import com.charonmc.CharonLogin;
import com.charonmc.events.PlayerAfterLoginListener;
import com.charonmc.utils.TokenUtils;
import com.charonmc.utils.mysql.SqlManager;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.player.*;
import org.bukkit.scheduler.BukkitRunnable;

public class PlayerListenerLogin implements Listener {
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event){
        event.getPlayer().setWalkSpeed(0f);
        event.getPlayer().teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
    }

    @EventHandler
    public void onPlayerHurt(EntityDamageEvent event) {
        // 取消一切生物伤害
        event.setCancelled(true);
    }

    @EventHandler
    public void onPlayerBreakBlock(BlockBreakEvent event) {
        event.setCancelled(true);
    }

    @EventHandler
    public void onBlockPlace(BlockPlaceEvent event){
        event.setCancelled(true);
    }

    @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event){
        if (!CharonLogin.loginPlayers.contains(event.getPlayer())){
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event){
        CharonLogin.loginPlayers.remove(event.getPlayer());
        CharonLogin.noLoginPlayers.remove(event.getPlayer());
        CharonLogin.loginErrorTime.remove(event.getPlayer());
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event){
        if (!CharonLogin.loginPlayers.contains(event.getPlayer())) {
            if (event.getFrom().getX() != event.getTo().getX() && event.getFrom().getZ() != event.getTo().getZ()) {
                // 允许玩家转动视角
                event.setCancelled(true);
            }
        } else {
            event.getPlayer().setWalkSpeed(0.2f);
        }
    }

    @EventHandler
    public void onPlayerCommand(PlayerCommandPreprocessEvent event){
        if (event.getMessage().startsWith("/reg") ||event.getMessage().startsWith("/l") || event.getMessage().startsWith("/AutoLogin") || event.getMessage().startsWith("/register") || event.getMessage().startsWith("/login") || event.getMessage().startsWith("/al") || event.getMessage().startsWith("/r")){
            return;
        } else {
            if (!CharonLogin.loginPlayers.contains(event.getPlayer())){
                event.setCancelled(true);
            }
        }
    }

    @EventHandler
    public void onPlayerHunger(FoodLevelChangeEvent event){
        event.setFoodLevel(20);
        event.setCancelled(true);
    }

    @EventHandler
    public void onPlayerAfterJoin(PlayerAfterLoginListener event){
        BukkitRunnable queryPlayerRegisterData = new BukkitRunnable() {
            @Override
            public void run() {
                boolean isPlayerRegister;
                try {
                    SqlManager sqlManager = new SqlManager("charonmc");
                    isPlayerRegister = sqlManager.createQuery()
                            .inTable("players")
                            .selectColumns("player_id")
                            .addCondition("Player_name", event.getPlayer().getName())
                            .build()
                            .execute()
                            .isNull();
                    if (isPlayerRegister){
                        event.getPlayer().sendMessage("");
                        event.getPlayer().sendMessage("§7 欢迎来到CharonMC,请先注册：");
                        event.getPlayer().sendMessage("§7 使用/reg <密码> <确认密码> 来注册。");
                        event.getPlayer().sendMessage("");
                    } else {
                        Object playerId = sqlManager.createQuery()
                                .inTable("players")
                                .selectColumns("player_id")
                                .addCondition("player_name", event.getPlayer().getName())
                                .build()
                                .execute()
                                .first();
                        Object autologin = sqlManager.createQuery()
                                .inTable("player_set")
                                .selectColumns("auto_login")
                                .addCondition("player_id", playerId)
                                .build()
                                .execute()
                                .first();
                        if ((int) autologin == 1){
                            //自动登录了
                            Object token = sqlManager.createQuery()
                                    .inTable("players")
                                    .selectColumns("token")
                                    .addCondition("player_id", playerId)
                                    .build()
                                    .execute()
                                    .first();
                            if (TokenUtils.getToken(event.getPlayer()).equals(token.toString())){
                                event.getPlayer().sendMessage("");
                                event.getPlayer().sendMessage("§a已自动登录");
                                event.getPlayer().sendMessage("");
                                CharonLogin.loginPlayers.add(event.getPlayer());
                                CharonLogin.autoLoginPlayer.put(event.getPlayer(), 24000);
                                BaseComponent bs2 = new TextComponent("§7您已开启§a自动登录服务 §7(点击关闭)");
                                bs2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent("§c关闭自动登录")}));
                                bs2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/AutoLogin"));
                                event.getPlayer().spigot().sendMessage(bs2);
                            } else {
                                CharonLogin.loginErrorTime.put(event.getPlayer(), 5);
                                CharonLogin.noLoginPlayers.put(event.getPlayer(), 60);
                                event.getPlayer().sendMessage("");
                                event.getPlayer().sendMessage("§7自动登录失败");
                                event.getPlayer().sendMessage("§7可能您的设备信息已变更，不必担心。");
                                event.getPlayer().sendMessage("§7请使用§f/l <密码> §7§l来登录。");
                                event.getPlayer().sendMessage("");
                            }
                        } else {
                            CharonLogin.loginErrorTime.put(event.getPlayer(), 5);
                            CharonLogin.noLoginPlayers.put(event.getPlayer(), 60);
                            event.getPlayer().sendMessage("");
                            event.getPlayer().sendMessage("§7欢迎回来");
                            event.getPlayer().sendMessage("§7你需先进行登录");
                            event.getPlayer().sendMessage("§7请使用§f/l <密码> §7来登录。");
                            event.getPlayer().sendMessage("");
                        }
                    }
                    sqlManager.close();
                } catch (Exception e) {
                    Bukkit.getServer().shutdown();
                    throw new RuntimeException(e);
                }
            }
        };
        queryPlayerRegisterData.runTaskAsynchronously(CharonLogin.instance);
    }
}
